import 'dart:math' as math;

import 'package:flutter/cupertino.dart' as IOS;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_app/utils/EventBus.dart';
import 'package:flutter_app/utils/http.dart';
import 'package:flutter_app/views/cardDetail.dart';
import 'package:flutter_app/widget/gsy_refresh_sliver.dart';
import 'package:flutter_app/widget/page_route_anim.dart';
import 'package:oktoast/oktoast.dart';



class WarningCard extends StatefulWidget {
  @override
  _WarningCard createState() => _WarningCard();
}

class _WarningCard extends State<WarningCard> with TickerProviderStateMixin {
  final GlobalKey<CupertinoSliverRefreshControlState> sliverRefreshKey =
  GlobalKey<CupertinoSliverRefreshControlState>();
  //  数据
  List warningData = [];
  //  获取列表
  var loading = true;
  var pageNum = 1;
  var pageSize = 20;
  bool isReposInit = true;
  var bus = new EventBus();
  var dialogIsShow = false;


  getList({motion:'normal'}) async{

    bus.on("push", (arg) {
      getList();
    });

    // tab页不同，查询不同
    var type = '1';
    if(tabIndex == 0){
      type = '1';
    }else{
      type = '0';
    }

    if(!loading) return;
    loading = false;

    if(motion == 'bottom'){
      pageNum++;
    }else{
      pageNum = 1;
    }
    ResultData list = await HttpRequest.post('/webauth/alarm/listAlarm', {
      'pageNum':pageNum,
      'pageSize':pageSize,
      'dealType':type // 未处理
    });
    if(dialogIsShow){
      Navigator.of(context).pop();
      dialogIsShow = false;
    }
    showToast("加载成功",duration: Duration(seconds: 1));
    loading = true;
    setState(() =>{
      if(motion == 'bottom'){
        warningData.addAll(list.data['list'])
      }else{
        warningData = list.data['list']
      },
      if(warningData.length == 0){
        isReposInit = false
      }
    });
  }

  TabController tabController;

  final ScrollController scrollController = new ScrollController();
  final int tabLength = 2;
  final double maxHeight = kToolbarHeight;
  final double minHeight = 30;
  final double tabIconSize = 30;
  final List tabText = ['未处理','已处理'];

  List<Widget> renderTabs(double shrinkOffset) {
    return List.generate(tabLength, (index) {
      return Column(
        children: <Widget>[
          Expanded(
            child: new Center(
              child: new Text(tabText[index]),
            ),
          )
        ],
      );
    });
  }

  // tab页面参数
  int tabIndex = 0;
  //  点击tab页面
  clickTab(index, context){
    setState(() {
      myDialog(context);
      tabIndex = index;
      getList();
    });
  }

  //  滑动查询
  @override
  void initState() {
    tabController = new TabController(length: tabLength, vsync: this);
    super.initState();
    getList();
    scrollController.addListener(()=>{
      if(scrollController.offset < -10){
        // 上滑
        getList()
      },
      if(scrollController.position.pixels> scrollController.position.maxScrollExtent){
        // 滑到最下
        getList(motion:'bottom')
      }
    });
  }

  @override
  void dispose(){
    // 为了避免内存泄漏，需要调用_controller.dispose
    scrollController.dispose();
    super.dispose();
  }

  setItem(index){
    if(warningData.length == 0){
      /// 注意，此处是多个
      return Container();
    }
    if(tabIndex == 0){
      return Container(
          margin:EdgeInsets.only(left:15, right: 15),
          padding:EdgeInsets.only(top:15, bottom: 5),
          child:Column(
            children: [
              Container(
                margin:EdgeInsets.only(bottom: 15),
                child: Row(
                  children: [
                    Text(warningData[index]["alarmTypeName"],style: TextStyle(fontWeight: FontWeight.w700))
                  ],
                ),
              ),
              Container(
                margin:EdgeInsets.only(bottom: 5),
                child: Row(
                  children: [
                    Text('抓拍时间:'+ warningData[index]["acquisitionTime"])
                  ],
                ),
              ),
              Container(
                margin:EdgeInsets.only(bottom: 5),
                child: Row(
                  children: [
                    Text('抓拍地点:'+ warningData[index]["acquisitionPlace"])
                  ],
                ),
              ),
              Container(
                child: Row(
                  children: [
                    Text('设备名称:'+ warningData[index]["deviceName"])
                  ],
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children:[Text('前往处理',style: TextStyle(color: Colors.blueAccent))],
              ),
            ],
          )
      );
    } else if(tabIndex == 1){
      return Container(
          margin:EdgeInsets.only(left:15, right: 15),
          padding:EdgeInsets.only(top:15, bottom: 5),
          child:Column(
            children: [
              Container(
                margin:EdgeInsets.only(bottom: 15),
                child: Row(
                  children: [
                    Text(warningData[index]["alarmTypeName"],style: TextStyle(fontWeight: FontWeight.w700))
                  ],
                ),
              ),
              Container(
                margin:EdgeInsets.only(bottom: 5),
                child: Row(
                  children: [
                    Text('抓拍时间:'+ warningData[index]["acquisitionTime"])
                  ],
                ),
              ),
              Container(
                margin:EdgeInsets.only(bottom: 5),
                child: Row(
                  children: [
                    Text('抓拍地点:'+ warningData[index]["acquisitionPlace"])
                  ],
                ),
              ),
              Container(
                child: Row(
                  children: [
                    Text('设备名称:'+ warningData[index]["deviceName"])
                  ],
                ),
              ),
            ],
          )
      );
    }

  }
  noBody(){
    return SliverList(
      delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
          if(isReposInit){
            if(warningData.length == 0){
              return new Container(
                  margin: EdgeInsets.all(10),
                  child: Align(
                    child: CircularProgressIndicator(),
                  )
              );
            }
            return Container();
          }else{
            return Container(
              margin: EdgeInsets.all(10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('暂无数据')
                ],
              )
            );
          }
        },
        childCount: 1
      ),
    );
  }

  renderListByIndex() {
    // int indexTab = tabController.index;
    // var list = dataList[indexTab];
    return SliverList(
      delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
//          if (index == warningData.length-1) {
//            return new Container(
//              margin: EdgeInsets.all(10),
//              child: Align(
//                child: CircularProgressIndicator(),
//              ),
//            );
//          }
          return Card(
            child: new Container(
              height: 160,
              alignment: Alignment.centerLeft,
              child: InkWell(
                  onTap: () {
                    Navigator.of(context).push(SlidingAroundRoute(CardDetail(id:warningData[index]["id"])));
                  },
                  child: setItem(index)
              ),
            ),
          );
        },
        childCount: warningData.length,
      ),
    );
  }
  Future myDialog(context){
    dialogIsShow = true;
    return showDialog<Null>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return GestureDetector(							// 手势处理事件
            onTap: (){
              //print('消失了');
              //Navigator.of(context).pop();				//退出弹出框
            },
            child: Container(								//弹出框的具体事件
              child: Material(
                color: Color.fromRGBO(0, 0, 0, 0.1),
                child: Center(
                  child: Text('加载中...',style:TextStyle(color: Colors.white),),
                ),
              ),
            )
        );
      }
    );
  }
  ///主列表
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: new Container(
        child: NotificationListener(
          onNotification: (ScrollNotification notification) {
            ///通知 CupertinoSliverRefreshControl 当前的拖拽状态
            sliverRefreshKey.currentState
                .notifyScrollNotification(notification);
            ///判断当前滑动位置是不是到达底部，触发加载更多回调
            return false;
          },
          child: new CustomScrollView(
            // 回弹效果
            physics: BouncingScrollPhysics(),
            controller: scrollController,
            slivers: <Widget>[
              ///动态放大缩小的tab控件
              SliverPersistentHeader(
                pinned: true,
                /// SliverPersistentHeaderDelegate 的实现
                delegate: GSYSliverHeaderDelegate(
                    maxHeight: maxHeight,
                    minHeight: minHeight,
                    changeSize: true,
                    vSync: this,
                    snapConfig: FloatingHeaderSnapConfiguration(
                      curve: Curves.bounceInOut,
                      duration: const Duration(milliseconds: 10),
                    ),
                    builder: (BuildContext context, double shrinkOffset,
                        bool overlapsContent) {
                      return Container(
                        height: maxHeight,
                        // color: Colors.white54,
                        decoration: BoxDecoration(
                          color: Colors.white70,
                          boxShadow: [
                            BoxShadow(
                                color: Colors.black12,
                                blurRadius: 10.0, //阴影模糊程度
                                spreadRadius: 1.0 //阴影扩散程度
                            )
                          ]),
                        child: TabBar(
                          indicatorColor: Colors.blue,
                          unselectedLabelColor: Colors.grey,
                          labelColor: Colors.blue,
                          controller: tabController,
                          tabs: renderTabs(shrinkOffset),
                          onTap: (index) {
                            clickTab(index, context);
                            // 回到顶部
                            scrollController.animateTo(0,
                                duration: Duration(milliseconds: 100),
                                curve: Curves.fastOutSlowIn);
                          },
                        ),
                      );
                    }),
              ),
              // 上部分的图标
              CupertinoSliverRefreshControl(
                key: sliverRefreshKey,
                refreshIndicatorExtent: 100,
                refreshTriggerPullDistance: 140,
                builder: buildSimpleRefreshIndicator,
              ),
              //noBody(),
              renderListByIndex()
            ],
          ),
        )
      ),
    );
  }
}

///动态头部处理
class GSYSliverHeaderDelegate extends SliverPersistentHeaderDelegate {
  GSYSliverHeaderDelegate(
      {@required this.minHeight,
        @required this.maxHeight,
        @required this.snapConfig,
        this.child,
        this.builder,
        this.vSync,
        this.changeSize = false});

  final double minHeight;
  final double maxHeight;
  final Widget child;
  final BuilderCard builder;
  final TickerProvider vSync;
  final bool changeSize;
  final FloatingHeaderSnapConfiguration snapConfig;
  AnimationController animationController;

  @override
  double get minExtent => minHeight;

  @override
  double get maxExtent => math.max(maxHeight, minHeight);


  @override
  TickerProvider get vsync => vSync;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    if (builder != null) {
      return builder(context, shrinkOffset, overlapsContent);
    }
    return child;
  }

  @override
  bool shouldRebuild(GSYSliverHeaderDelegate oldDelegate) {
    return true;
  }

  @override
  FloatingHeaderSnapConfiguration get snapConfiguration => snapConfig;
}

typedef Widget BuilderCard(
    BuildContext context, double shrinkOffset, bool overlapsContent);

Widget buildSimpleRefreshIndicator(
    BuildContext context,
    RefreshIndicatorMode refreshState,
    double pulledExtent,
    double refreshTriggerPullDistance,
    double refreshIndicatorExtent,
    ) {
  const Curve opacityCurve = Interval(0.4, 0.8, curve: Curves.easeInOut);
  return Align(
    alignment: Alignment.bottomCenter,
    child: Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: refreshState != RefreshIndicatorMode.refresh
          ? Opacity(
        opacity: opacityCurve.transform(
            math.min(pulledExtent / refreshTriggerPullDistance, 1.0)),
        child: const Icon(
          IOS.CupertinoIcons.down_arrow,
          color: IOS.CupertinoColors.inactiveGray,
          size: 36.0,
        ),
      )
          : Opacity(
        opacity: opacityCurve
            .transform(math.min(pulledExtent / refreshIndicatorExtent, 1.0)),
        child: const IOS.CupertinoActivityIndicator(radius: 14.0),
      ),
    ),
  );
}
